package com.chb.test;

import com.chb.utils.ESClient;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.junit.Test;

import java.io.IOException;

public class IndexDemo {

    String index = "person";
    RestHighLevelClient client = ESClient.getClient();

    @Test
    public void createIndex() throws IOException {
        // 1、创建setting
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);

        // 2、设置mappings
        XContentBuilder mappings = JsonXContent.contentBuilder()
                .startObject()
                .startObject("properties")
                .startObject("name")
                .field("type", "text")
                .endObject()
                .startObject("age")
                .field("type", "integer")
                .endObject()
                .startObject("birthday")
                .field("type", "date")
                .field("format", "yyyy-MM-dd")
                .endObject()
                .endObject()
                .endObject();

        // 3、将settings和mappings封装到Request对象
        CreateIndexRequest request = new CreateIndexRequest(index).settings(settings).mapping(mappings);

        // 4、通过client对象连接ES并创建索引
        CreateIndexResponse resp = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(resp);
    }


    @Test
    public void existIndex() throws IOException {
        // 1、创建Request对象
        GetIndexRequest request = new GetIndexRequest(index);
        // 2、通过client对象执行
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //3、打印返回结果
        System.out.println(exists);
    }
    
    @Test
    public void deleteIndex() throws IOException {
        DeleteIndexRequest request = new DeleteIndexRequest(index);

        // 删除
        client.indices().delete(request, RequestOptions.DEFAULT);
    }


}
